import { _decorator, Component, Node, Collider2D, Contact2DType, IPhysics2DContact, BoxCollider2D, v2, UITransform, CircleCollider2D, Sprite, Vec3, Size, Vec2 } from 'cc';
import { BasicComponet } from '../../Init/Basic/BasicComponet';
import { GlobalConfig } from '../../Init/Config/GlobalConfig';
import { GlobalEnum } from '../../Init/Config/GlobalEnum';
const { ccclass, property } = _decorator;

@ccclass('Barrier2D')
export class Barrier2D extends BasicComponet {

    //叠加的速度
    addSpd = GlobalConfig.Barrier.addSpd;
    maxX = 0;
    minX = 0;

    setData(d: { parent: Node, p: Vec3, r: Vec3, s: Vec2 }) {
        this.node.parent = d.parent;
        this.node.setPosition(d.p);
        this.node.eulerAngles = d.r;
        let trans = this.node.getComponent(UITransform);
        trans.setContentSize(d.s.x, d.s.y);
        // 注册单个碰撞体的回调函数
        let collider = this.getComponent(BoxCollider2D);
        if (collider) {
            collider.size = trans.contentSize;
            collider.apply();
            let cw = collider.size.width * 0.5;
            this.maxX = cw + this.node.worldPosition.x;
            this.minX = -cw + this.node.worldPosition.x;

            collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
            collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
        }
        //
        let sp = this.node.getComponent(Sprite);
        if (sp) {
            sp.enabled = GlobalConfig.isShow2dCollider;
        }

    }

    onDisable() {
    }
    /**检测分组 //touchPlayerId 僵尸 平民*/
    checkGroupArr = [1 << 1, 1 << 5, 1 << 6];
    // 只在两个碰撞体开始接触时被调用一次
    onBeginContact(selfCollider: BoxCollider2D, otherCollider: CircleCollider2D, contact: IPhysics2DContact | null) {
        // 被碰撞的物体-速度修正

        if (otherCollider.body[GlobalEnum.ExtralProp.addLineVec] && this.checkGroupArr.indexOf(otherCollider.group) >= 0) {
            //上下方向
            if (otherCollider.node.worldPosition.x <= this.maxX &&
                otherCollider.node.worldPosition.x >= this.minX) {
                //平民 X速度方向随机
                let x = this.addSpd.x;
                if (otherCollider.group == 1 << 5) {
                    x *= Math.random() > 0.5 ? 1 : -1;
                }
                otherCollider.body[GlobalEnum.ExtralProp.addLineVec].x = otherCollider.body.linearVelocity.x > 0 ? x : -x;
            } else {
                otherCollider.body[GlobalEnum.ExtralProp.addLineVec].x = 0;
                otherCollider.body[GlobalEnum.ExtralProp.addLineVec].y = otherCollider.body.linearVelocity.y > 0 ? this.addSpd.y : -this.addSpd.y;
            }
        }
    }

    onEndContact(selfCollider: BoxCollider2D, otherCollider: CircleCollider2D, contact: IPhysics2DContact | null) {
        // 被碰撞的物体-速度修正
        if (otherCollider.body[GlobalEnum.ExtralProp.addLineVec] && this.checkGroupArr.indexOf(otherCollider.group) >= 0) {
            otherCollider.body[GlobalEnum.ExtralProp.addLineVec].set(0, 0);
        }
    }

}

